package cn.nexd.map.location.collector.core;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;

import cn.nexd.map.location.collector.BasebandCollector;
import cn.nexd.map.location.collector.Collector;
import cn.nexd.map.location.collector.CollectorConfig;
import cn.nexd.map.location.collector.UserIdUtils;
import cn.nexd.map.location.collector.bean.BasebandDataResult;
import cn.nexd.map.location.collector.listener.BasebandCollectorResultListener;
import cn.nexd.map.location.collector.listener.DefaultCollectorResultListener;
import cn.nexd.map.location.utils.ObjectPool;
import cn.nexd.map.utils.BasicPhoneInformation;


/**
 * 获取移动设备信息任务类
 * Created by lawrence on 2015/11/24.
 */
public class BasebandCollectorTask extends BasebandCollector {

    //  定义可以获取到的基带信号类型
    public static final int TYPE_GSM = 1;
    public static final int TYPE_CDMA = 2;
    public static final int TYPE_LTE = 3;
    public static final int TYPE_WCDMA = 4;

    private TelephonyManager telephonyManager;
    private static final int OBJECT_POOL_SIZE = 50;
    //    private BasebandCollectorResultListener basebandCollectorResultListener;
//    private BasebandCollectorHandler basebandCollectorHandler;
//    private BasebandCollectorThread basebandCollectorThread;
//    private ObjectPool<BasebandDataResult> basebandDataResultObjectPool;

//    private CellInfoGsm cellInfoGsm;
//    private CellInfoWcdma cellInfoWcdma;
//    private CellInfoCdma cellInfoCdma;
//    private CellInfoLte cellInfoLte;

//    private static int basebandType;

    private static final int CELLINFO_SUCCESS = 10001;
    private static final int CELLINFO_FAILED = 10002;

    protected BasebandCollectorTask(Context context, CollectorConfig collectorConfig, BasebandCollectorResultListener basebandCollectorResultListener) {
        super(context, basebandCollectorResultListener, collectorConfig);
        ObjectPool.ObjectPoolFactory<BasebandDataResult> cellDataResultObjectPoolFactory = new ObjectPool.ObjectPoolFactory<BasebandDataResult>() {
            @Override
            public BasebandDataResult createObject() {
                return new BasebandDataResult();
            }
        };

//        basebandDataResultObjectPool = new ObjectPool<>(cellDataResultObjectPoolFactory, OBJECT_POOL_SIZE);
    }

    protected BasebandCollectorTask(Context context, CollectorConfig collectorConfig) {
        super(context, null, collectorConfig);
        ObjectPool.ObjectPoolFactory<BasebandDataResult> cellDataResultObjectPoolFactory = new ObjectPool.ObjectPoolFactory<BasebandDataResult>() {
            @Override
            public BasebandDataResult createObject() {
                return new BasebandDataResult();
            }
        };
//        basebandDataResultObjectPool = new ObjectPool<>(cellDataResultObjectPoolFactory, OBJECT_POOL_SIZE);
    }


    protected BasebandCollectorTask(Context context, BasebandCollectorResultListener basebandCollectorResultListener) {
        super(context, basebandCollectorResultListener, null);
        ObjectPool.ObjectPoolFactory<BasebandDataResult> cellDataResultObjectPoolFactory = new ObjectPool.ObjectPoolFactory<BasebandDataResult>() {
            @Override
            public BasebandDataResult createObject() {
                return new BasebandDataResult();
            }
        };
//        basebandDataResultObjectPool = new ObjectPool<>(cellDataResultObjectPoolFactory, OBJECT_POOL_SIZE);
    }

//    public abstract int getBaseBandType();

    @Override
    public boolean initilazeCollector() {

        if (basebandCollectorResultListener == null) {
            basebandCollectorResultListener = DefaultCollectorResultListener.getBasebandCollectorResultListener();
        }

        if (collectorConfig == null) {
            collectorConfig = new CollectorConfig.Builder().build();
        }

        if (context == null) {
            basebandCollectorResultListener.onFailed(UserIdUtils.getInstance().getTask_Id(), Collector.FAILED_ID_CONTEXT_NULL, "the context is null");
            return false;
        }

        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if (telephonyManager == null) {
            basebandCollectorResultListener.onFailed(UserIdUtils.getInstance().getTask_Id(), Collector.FAILED_ID_SCAN_MODE_NONE, "the baseband signal not available");
            return false;
        }

        if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_UNKNOWN) {
            basebandCollectorResultListener.onFailed(UserIdUtils.getInstance().getTask_Id(), Collector.FAILED_ID_MANAGER_INIT_FAILED, "the sim`s state is unknow");
            return false;
        }


//        basebandType = getBaseBandType();

        return true;
    }

    @Override
    public boolean startCollector() {
        telephonyManager.listen(new BasebandSignalStrengthListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        return true;
    }

    @Override
    public boolean stopCollector() {
        if (telephonyManager != null) {
//            telephonyManager.listen(null, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
            telephonyManager = null;
        }

        if (basebandCollectorResultListener != null) {
            basebandCollectorResultListener = null;
        }

        return true;
    }


    private class BasebandSignalStrengthListener extends PhoneStateListener {

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);

            // 暂停后，telephoneManager 为 null ，这时候，不需要进行数据获取
            if (telephonyManager == null) {
                return;
            }

            BasebandDataResult basebandDataResult = new BasebandDataResult();
            basebandDataResult.setId(UserIdUtils.getInstance().getTask_Id());
            basebandDataResult.setUserId(UserIdUtils.getInstance().getUserId(context));
            basebandDataResult.setCarrierType(BasicPhoneInformation.getInstance(context).getProvider());
            basebandDataResult.setTimestamp(System.currentTimeMillis());

            String singalinfo = signalStrength.toString();
            String[] parts = singalinfo.split(" ");
            int ltedbm = Integer.parseInt(parts[9]);

            int asu = signalStrength.getGsmSignalStrength();
            int dbm = -113 + 2 * asu;

            if (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
                basebandDataResult.setSignalStrength(ltedbm);
                basebandDataResult.setBasebandType("LTE");
            } else if (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSDPA
                    || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSPA
                    || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_HSUPA
                    || telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS) {
                basebandDataResult.setBasebandType("WCDMA");
                basebandDataResult.setSignalStrength(dbm);
            } else {
                basebandDataResult.setBasebandType("GSM");
                basebandDataResult.setSignalStrength(dbm);
            }

            if (basebandCollectorResultListener != null && basebandDataResult != null) {
                basebandCollectorResultListener.onSuccess(UserIdUtils.getInstance().getTask_Id(), basebandDataResult);
            } else {
                if (basebandCollectorResultListener != null) {
                    basebandCollectorResultListener.onFailed(UserIdUtils.getInstance().getTask_Id(), Collector.FAILED_ID_CONTEXT_NULL, "结果为空");
                }
            }
        }

    }
}
